<!--
 * @Description: 砍价活动管理列表
 * @Author: liyujie
 * @Date: 2021/04/19
 * @Last Modified by: liyujie
 * @Last Modified time: 2021/04/19
-->
<template>
    <div class="wrapper">
        <div class="content-wrapper">
            <!-- header -->
            <div class="header">
                <div class="header-title">
                    砍价活动管理
                </div>
                <div class="add-btn">
                    <el-button
                        type="primary"
                        size="medium"
                        icon="el-icon-plus"
                        @click="showEditDialog('add')"
                    >
                        新建活动
                    </el-button>
                </div>
            </div>
            <!-- /header -->
            <!-- 筛选-->
            <div class="filter-view">
                <div class="header-new-box">
                    <p class="header-new-box-title">
                        活动时间
                    </p>
                    <el-date-picker
                        v-model="dateTimeRange"
                        type="datetimerange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :default-time="['00:00:00', '23:59:59']"
                        size="medium"
                        style="width: 400px"
                        value-format="timestamp"
                    />
                </div>
                <div class="header-new-box">
                    <el-button
                        type="primary"
                        size="small"
                        @click="getTableData(1)"
                    >
                        查询
                    </el-button>
                </div>
            </div>
            <!--筛选-->

            <!-- table -->
            <div class="table-wrapper">
                <el-table
                    :data="tableData"
                    height="100%"
                    style="width: 100%;"
                    ref="table"
                    class="data-table"
                    v-loading="tableLoading"
                >
                    <el-table-column
                        label="序号"
                        align="center"
                        width="50"
                        type="index"
                    />
                    <el-table-column
                        label="活动时间"
                        align="left"
                        :formatter="emptyFormatter"
                        min-width="160"
                    >
                        <template slot-scope="scope">
                            {{ scope.row.activity_start_time * 1000 | dateFormatter('yyyy/MM/dd HH:mm:ss') }} - {{ scope.row.activity_end_time * 1000 | dateFormatter('yyyy/MM/dd HH:mm:ss') }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="初始砍价比例"
                        show-overflow-tooltip
                        align="center"
                        width="110"
                        :formatter="emptyFormatter"
                    >
                        <template slot-scope="scope">
                            {{ Number(scope.row.apply_discount_percent).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="砍价浮动区间"
                        show-overflow-tooltip
                        align="center"
                        width="130"
                        :formatter="emptyFormatter"
                    >
                        <template slot-scope="scope">
                            【{{ Number(scope.row.bargain_money_min_rate).toFixed(2) }}, {{ Number(scope.row.bargain_money_max_rate).toFixed(2) }}】
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="H5/APP新用户系数"
                        show-overflow-tooltip
                        align="center"
                        width="150"
                        :formatter="emptyFormatter"
                    >
                        <template slot-scope="scope">
                            {{ scope.row.bargain_weight_for_new_user }} / {{ scope.row.new_user_bargain_weight }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="已发放数/本场商品数"
                        show-overflow-tooltip
                        align="center"
                        width="150"
                        :formatter="emptyFormatter"
                    >
                        <template slot-scope="scope">
                            {{ scope.row.goods_success_count ? scope.row.goods_success_count : 0 }} /
                            {{ scope.row.goods_total_stock_origin ? scope.row.goods_total_stock_origin : 0 }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="已发放数/本场优惠券数"
                        show-overflow-tooltip
                        align="center"
                        width="200"
                        :formatter="emptyFormatter"
                    >
                        <template slot-scope="scope">
                            {{ scope.row.coupon_success_count ? scope.row.coupon_success_count : 0 }} /
                            {{ scope.row.coupons_total_stock_origin ? scope.row.coupons_total_stock_origin : 0 }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="已发放数/本场红包数"
                        show-overflow-tooltip
                        align="center"
                        width="150"
                        :formatter="emptyFormatter"
                    >
                        <template slot-scope="scope">
                            {{ scope.row.red_packet_success_count ? scope.row.red_packet_success_count : 0 }} /
                            {{ scope.row.red_packet_total_stock_origin ? scope.row.red_packet_total_stock_origin : 0 }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="join_count"
                        label="参与活动人数"
                        show-overflow-tooltip
                        align="center"
                        width="120"
                        :formatter="emptyFormatter"
                    />
                    <el-table-column
                        label="活动状态"
                        align="center"
                        :formatter="emptyFormatter"
                    >
                        <template slot-scope="scope">
                            <div class="status-wrapper">
                                <div
                                    class="status-dot"
                                    :class="['status-dot', scope.row.status === 1 ? 'success' : 'normal']"
                                />
                                <div>{{ scope.row.status | statusFilter }}</div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="admin_true_name"
                        label="操作人"
                        align="center"
                        :formatter="emptyFormatter"
                    />
                    <el-table-column
                        label="操作"
                        align="left"
                        width="160"
                        fixed="right"
                    >
                        <template slot-scope="scope">
                            <div class="option-btn-group">
                                <el-button
                                    type="text"
                                    @click="showEditDialog('edit', scope.row)"
                                >
                                    编辑
                                </el-button>
                                <el-button
                                    type="text"
                                    @click="handleRoute('bargainGoodsList', {activity_no: scope.row.activity_no})"
                                >
                                    查看商品
                                </el-button>
                                <el-button
                                    type="text"
                                    @click="handleRoute('bargainActivityInitiatorList', {activity_no: scope.row.activity_no})"
                                >
                                    查看参与用户
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- /table -->

            <!-- /分页 -->
            <div class="pagination-wrapper clearfix">
                <el-pagination
                    layout="total, prev, pager, next, jumper"
                    background
                    :current-page.sync="page.now_page"
                    :total="page.total_count"
                    :page-size="page.page_size"
                    @current-change="getTableData"
                />
            </div>
        </div>
        <el-dialog
            :title="editDialog.type === 'add' ? '新建活动' : '编辑活动'"
            :visible.sync="editDialog.visible"
            width="680px"
            @close="handleDialogClose"
        >
            <el-form
                :model="editForm"
                :rules="editRules"
                label-position="right"
                ref="ruleForm"
                label-width="140px"
                class="form-wrap"
                @submit.native.prevent
            >
                <el-form-item
                    label="开始时间"
                >
                    <div class="inline-form-wrapper">
                        <el-form-item
                            label-width="0px"
                            prop="activity_start_time"
                        >
                            <el-date-picker
                                v-model="editForm.activity_start_time"
                                type="datetime"
                                default-time="00:00:00"
                                size="medium"
                                placeholder="请选择开始时间"
                                style="width: 200px"
                                :disabled="editForm.status === 1"
                                value-format="timestamp"
                            />
                        </el-form-item>
                        <div class="link">-</div>
                        <el-form-item
                            label-width="0px"
                            prop="activity_end_time"
                        >
                            <el-date-picker
                                v-model="editForm.activity_end_time"
                                type="datetime"
                                default-time="23:59:59"
                                size="medium"
                                placeholder="请选择结束时间"
                                style="width: 200px"
                                value-format="timestamp"
                            />
                        </el-form-item>
                    </div>
                </el-form-item>
                <el-form-item
                    label="新用户H5系数"
                    prop="bargain_weight_for_new_user"
                >
                    <el-input
                        v-model="editForm.bargain_weight_for_new_user"
                        size="medium"
                        clearable
                        style="width: 440px"
                    />
                </el-form-item>
                <el-form-item
                    label="新用户APP系数"
                    prop="new_user_bargain_weight"
                >
                    <el-input
                        v-model="editForm.new_user_bargain_weight"
                        size="medium"
                        clearable
                        style="width: 440px"
                    />
                </el-form-item>
                <el-form-item
                    label="初始砍价比例"
                    prop="apply_discount_percent"
                >
                    <el-input
                        v-model="editForm.apply_discount_percent"
                        size="medium"
                        clearable
                        style="width: 440px"
                    >
                        <span
                            slot="suffix"
                            style="margin-right: 6px"
                        >%</span>
                    </el-input>
                </el-form-item>
                <el-form-item
                    label="砍价浮动区间"
                >
                    <div class="inline-form-wrapper">
                        <el-form-item
                            label-width="0px"
                            prop="bargain_money_min_rate"
                        >
                            <el-input
                                v-model="editForm.bargain_money_min_rate"
                                size="medium"
                                clearable
                                style="width: 200px"
                            />
                        </el-form-item>
                        <div class="link">-</div>
                        <el-form-item
                            label-width="0px"
                            prop="bargain_money_max_rate"
                        >
                            <el-input
                                v-model="editForm.bargain_money_max_rate"
                                size="medium"
                                clearable
                                style="width: 200px"
                            />
                        </el-form-item>
                    </div>
                </el-form-item>
                <div class="btn-group">
                    <el-button
                        size="medium"
                        style="width: 120px"
                        @click="editDialog.visible = false"
                    >
                        取消
                    </el-button>
                    <el-button
                        type="primary"
                        size="medium"
                        style="width: 120px;margin-left: 24px"
                        @click="handleSubmit"
                    >
                        保存
                    </el-button>
                </div>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import { back } from '@/mixin/back';
import {deepClone} from "@/assets/js/utils";
const numberReg = /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0)$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/;

export default {
    name: 'BargainActivityList',
    mixins: [back],
    components: {},
    data() {
        const checkEndTime = (rule, value, callback) => {
            if(value > this.editForm.activity_start_time) {
                callback();
            } else {
                callback(new Error('结束时间需要大于开始时间'));
            }
        };
        const checkPercent = (rule, value, callback) => {
            if(Number(value) >= 0 && Number(value) < 100) {
                callback();
            } else {
                callback(new Error('初始砍价比例应该大于等于0小于100'));
            }
        };
        const checkFloat = (rule, value, callback) => {
            if(0 < Number(value) && Number(value) < 2) {
                callback();
            } else {
                callback(new Error('砍价浮动区间应该大于0小于2'));
            }
        };
        const checkFloatMax = (rule, value, callback) => {
            if(value > this.editForm.bargain_money_min_rate) {
                callback();
            } else {
                callback(new Error('最大浮动区间需要大于最小浮动区间'));
            }
        };

        return {
            filterData: {
                activity_start_time: '',
                activity_end_time: '',
            },
            tableData: [],
            tableLoading: false,
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 20
            },
            dateTimeRange: [],
            // 编辑弹窗
            editDialog: {
                visible: false,
                // add新建 edit编辑
                type: 'add',
            },
            editForm: {
                activity_no: '',
                // 活动状态 编辑时候禁用开始时间
                status: '',
                activity_start_time: '',
                activity_end_time: '',
                // h5用户比例系数
                bargain_weight_for_new_user: '',
                // app系数
                new_user_bargain_weight: '',
                // 初始砍价比例
                apply_discount_percent: '',
                // 砍价浮动区间
                bargain_money_min_rate: '',
                bargain_money_max_rate: '',
            },
            editRules: {
                activity_start_time: [
                    {required: true, message: '请选择活动开始时间', trigger: 'change'},
                ],
                activity_end_time: [
                    {required: true, message: '请选择活动结束时间', trigger: 'change'},
                    {validator: checkEndTime, trigger: 'change'}
                ],
                bargain_weight_for_new_user: [
                    {required: true, message: '请填写新用户H5系数', trigger: 'blur'},
                    {pattern: /^\d{1,}$/, message: '新用户H5系数必须为数字', trigger: 'blur'}
                ],
                new_user_bargain_weight: [
                    {required: true, message: '请填写新用户APP系数', trigger: 'blur'},
                    {pattern: /^\d{1,}$/, message: '新用户APP系数系数必须为数字', trigger: 'blur'}
                ],
                apply_discount_percent: [
                    {required: true, message: '请填写初始砍价比例', trigger: 'blur'},
                    {pattern: numberReg, message: '初始砍价比例必须为数字且保留两位小数', trigger: 'blur'},
                    { validator: checkPercent, trigger: 'blur' }
                ],
                bargain_money_min_rate: [
                    {required: true, message: '请填写砍价浮动区间', trigger: 'blur'},
                    {pattern: numberReg, message: '砍价浮动区间必须为数字', trigger: 'blur'},
                    {validator: checkFloat, trigger: 'blur'},
                ],
                bargain_money_max_rate: [
                    {required: true, message: '请填写砍价浮动区间', trigger: 'blur'},
                    {pattern: numberReg, message: '砍价浮动区间必须为数字', trigger: 'blur'},
                    {validator: checkFloat, trigger: 'blur'},
                    {validator: checkFloatMax, trigger: 'blur'}
                ],
            },
            authResult: {}
        };
    },
    computed: {},
    watch: {
        dateTimeRange(value) {
            this.filterData.activity_start_time = value ? value[0] / 1000 : '';
            this.filterData.activity_end_time = value ? value[1] / 1000 : '';
            this.getTableData(1);
        }
    },
    filters: {
        statusFilter(val) {
            switch (val) {
                case 0:
                    return '未开始';
                case 1:
                    return '进行中';
                case 2:
                    return '已过期';
                default:
                    return '--';
            }
        },
    },
    mounted() {
        this.$store.commit('SET_HEADER', [{title: "APP后台"}, {title: '商城'}, {title: '砍价活动'}, {title: '活动管理'}]);
        this.authResult = this.$route.meta.authResult;
        this.getTableData();
    },

    methods: {

        /**
         * @description 获取列表数据
         * @param page
         */
        getTableData(page) {
            this.tableLoading = true;
            let params = { ...this.filterData };

            params.page_id = page || this.page.now_page;
            this.$post('/student/shop_tool_bargain%5Cactivity%5Cget_list', params, res => {
                if (res.code === 1) {
                    this.tableData = res.data.list;
                    this.page = res.data.page;
                } else {
                    this.$notify({
                        title: '提示',
                        message: res.msg,
                        type: 'warning'
                    });
                }
                this.tableLoading = false;
            });
        },

        /**
         * 路由跳转
         * @param routeName
         * @param query
         */
        handleRoute(routeName, query) {
            this.$router.push({
                name: routeName,
                query
            });
        },

        /**
         * @description 过滤函数
         */
        emptyFormatter(row, column, val) {
            if (!val) return '--';
            return val;
        },

        /**
         * 显示编辑弹窗
         * @param type
         * @param row
         */
        showEditDialog(type, row) {
            if(!this.authResult.auth_add) {
                this.$notify({
                    title: '提示',
                    message: '请联系管理员添加权限',
                    type: 'warning',
                    duration: 2000
                });
                return false;
            }
            this.editDialog.type = type;
            this.editDialog.visible = true;
            if(row) {
                // 填写字段
                this.editForm.activity_no = row.activity_no;
                this.editForm.status = row.status;
                this.editForm.activity_start_time = row.activity_start_time * 1000;
                this.editForm.activity_end_time = row.activity_end_time * 1000;
                this.editForm.bargain_weight_for_new_user = row.bargain_weight_for_new_user;
                this.editForm.new_user_bargain_weight = row.new_user_bargain_weight;
                this.editForm.apply_discount_percent = Number(row.apply_discount_percent).toFixed(2);
                this.editForm.bargain_money_min_rate = Number(row.bargain_money_min_rate).toFixed(2);
                this.editForm.bargain_money_max_rate = Number(row.bargain_money_max_rate).toFixed(2);
            }
        },

        /**
         * @description 提交
         */
        handleSubmit() {
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    let params = deepClone(this.editForm);

                    params.activity_start_time = params.activity_start_time / 1000;
                    params.activity_end_time = params.activity_end_time / 1000;
                    this.$post('/student/shop_tool_bargain%5Cactivity%5Csave', params, resp => {
                        if (resp.code === 1) {
                            this.editDialog.visible = false;
                            this.getTableData();
                            this.$notify({
                                title: '提示',
                                message: '保存成功',
                                duration: 2000,
                                type: 'success'
                            });
                        } else {
                            this.$notify({
                                title: '提示',
                                message: resp.msg,
                                duration: 2000,
                                type: 'warning'
                            });
                        }
                    });
                }
            });
        },

        /**
         * 弹窗关闭清空表单
         */
        handleDialogClose() {
            this.editForm.activity_no = '';
            this.editForm.status = '';
            this.editForm.activity_start_time = '';
            this.editForm.activity_end_time = '';
            this.editForm.bargain_weight_for_new_user = '';
            this.editForm.new_user_bargain_weight = '';
            this.editForm.apply_discount_percent = '';
            this.editForm.bargain_money_min_rate = '';
            this.editForm.bargain_money_max_rate = '';
            this.$refs.ruleForm.clearValidate();
        }
    }
};
</script>

<style lang="less" scoped>
.wrapper {
    width: 100%;

    .content-wrapper {
        display: flex;
        height: calc(100% - 24px);
        flex-direction: column;
        position: relative;
        margin: 12px;
        background: #fff;
        box-sizing: border-box;

        /*header*/

        .header {
            height: 68px;
            padding: 24px;
            box-sizing: border-box;
            box-shadow: 0px -1px 0px 0px #F0F2F5;
            display: flex;
            align-items: center;
            border-bottom: 1px solid #F0F2F5;
            justify-content: space-between;

            .header-title {
                color: #333333;
                font-size: 20px;
                height: 20px;
                font-weight: 500;
                position: relative;
                margin: 24px 0 24px 12px;

                &::before {
                    content: '';
                    position: absolute;
                    left: -8px;
                    top: -1px;
                    width: 3px;
                    height: 20px;
                    background: #1890FF;
                }
            }
        }

        /*筛选*/

        .filter-view {
            box-sizing: border-box;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            padding: 0 24px;
            margin-top: 12px;

            .header-new-box {
                display: flex;
                align-items: center;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #333333;
                white-space: nowrap;
                margin-right: 24px;
                margin-bottom: 12px;

                &-title {
                    margin-right: 16px;
                    white-space: nowrap;
                }
            }
        }

        // 表格
        .table-wrapper {
            padding: 0 24px;
            flex: 1;
            height: 0;
        }

        .status-wrapper {
            display: flex;
            align-items: center;
            justify-content: center;

            .status-dot {
                width: 6px;
                height: 6px;
                border-radius: 50%;
                margin-right: 5px;

                &.success {
                    background: #4CD964;
                }

                &.danger {
                    background: #FF3030;
                }

                &.warning {
                    background: #FFA72D;
                }

                &.normal {
                    background: #C2C2C2;
                }
            }
        }

        /* 分页 */

        .pagination-wrapper {
            padding: 12px 24px;
            .el-pagination {
                float: right;
                padding: 0;
                background-color: transparent;
            }
        }
    }

    // 编辑弹窗
    .form-wrap {
        .inline-form-wrapper {
            display: flex;
            align-items: center;
            .link {
                margin: 0 18px;
            }
        }
        .tips {
            font-size: 12px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #999999;
            margin-left: 12px;
        }
        .btn-group {
            display: flex;
            justify-content: center;
            margin-top: 48px;
        }
    }

    /deep/ .el-dialog__header {
        padding-top: 10px;
        box-shadow:0 1px 0 0 rgba(233,233,233,1);
        display: flex;
        align-items: center;
        background: #FAFAFA;
        border-radius: 4px 4px 0 0;
        .el-dialog__title {
            font-weight: 500;
            color: #333;
            font-size: 14px;
        }
        .el-icon-close:before {
            color: rgb(194,194,194);
            font-size: 17px;
            font-weight: bold;
        }
        .el-dialog__headerbtn {
            top: 14px;
        }
    }
    .dialog-footer {
        display: flex;
        justify-content: center;
    }
    /deep/ .el-textarea__inner {
        resize: none;
    }
    .data-table {
        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
        // 操作按钮
        .option-btn-group {
            .el-button {
                margin-left: 0;
                margin-right: 10px;
                padding-top: 10px;
                padding-bottom: 10px;
            }
        }
    }
}
</style>
